<?php
/*
|--------------------------------------------------------------------------
| Common function method
|--------------------------------------------------------------------------
*/

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Server\ServerFactory;
use Hyperf\Context\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * 输出多个参数
 */
if (!function_exists('dd')) {
    function dd(...$vars)
    {
        if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) {
            header('HTTP/1.1 500 Internal Server Error');
        }
        foreach ($vars as $v) {
            var_dump($v);
        }
        exit(1);
    }
}

if (!function_exists('container')) {
    /**
     * 容器实例
     * @return ContainerInterface
     */
    function container()
    {
        return ApplicationContext::getContainer();
    }
}

if (!function_exists('config')) {
    function config()
    {
        return container()->get(\Hyperf\Config\Config::class);
    }
}

if (!function_exists('redis')) {
    /**
     * Redis 客户端实例
     * @param string $name
     * @return mixed
     * @throws mixed
     */
    function redis($name = 'default')
    {
        return container()->get(\Hyperf\Redis\RedisFactory::class)->get($name);
    }
}

if (!function_exists('guzzle_http')) {

    /**
     * 创建 guzzle-http 客户端
     * @return mixed
     * @throws mixed
     */
    function guzzle_http(): GuzzleHttp\Client
    {
        return container()->get(ClientFactory::class)->create();
    }
}

if (!function_exists('server')) {
    /**
     * Server 实例 基于 Swoole Server
     * @return mixed
     * @throws mixed
     */
    function server()
    {
        return container()->get(ServerFactory::class)->getServer()->getServer();
    }
}

if (!function_exists('cache')) {
    /**
     * 缓存实例 简单的缓存
     * @return mixed
     * @throws mixed
     */
    function cache()
    {
        return container()->get(Psr\SimpleCache\CacheInterface::class);
    }
}

if (!function_exists('stdout_log')) {
    /**
     * 控制台日志实例
     * @return mixed
     * @throws mixed
     */
    function stdout_log()
    {
        return container()->get(StdoutLoggerInterface::class);
    }
}

if (!function_exists('logger')) {
    /**
     * 文件日志实例
     * @param string $name
     * @param string $group default,或者tool
     * @return mixed
     * @throws mixed
     */
    function logger(string $name = 'app', string $group = 'tool')
    {
        return container()->get(LoggerFactory::class)->get($name, $group);
    }
}

if (!function_exists('request')) {
    /**
     * Http 请求实例
     * @return mixed
     * @throws mixed
     */
    function request()
    {
        return container()->get(ServerRequestInterface::class);
    }
}

if (!function_exists('response')) {
    /**
     * Http 响应实例
     * @return mixed
     * @throws mixed
     */
    function response()
    {
        return container()->get(ResponseInterface::class);
    }
}

if (!function_exists('event')) {
    /**
     * Dispatch an event and call the listeners.
     */
    function event()
    {
        return container()->get(Psr\EventDispatcher\EventDispatcherInterface::class);
    }
}

/**
 * 推送消息到 Redis 订阅中
 *
 * @param string $chan
 * @param string|array $message
 */
if (!function_exists('pushRedisSubscribe')) {
    function pushRedisSubscribe(string $chan, $message)
    {
        redis()->publish($chan, is_string($message) ? $message : json_encode($message));
    }
}

/**
 * 重新格式化数组
 *
 * @param array $arr 二维数组
 * @param string $field 以指定的字段名为新数据的key
 */
if (!function_exists('reformArr')) {
    function reformArr($arr = [], $field = '')
    {
        $new_arr = [];
        if (!is_array($arr) || empty($arr) || $field == '') {
            return $new_arr;
        }
        foreach ($arr as $av) {
            if (!is_array($av)) {
                break;
            }
            $fields = explode('.', $field);
            $tmp = $av;
            foreach ($fields as $f) {
                if (!array_key_exists($f, $tmp)) {
                    break;
                }
                $tmp = $tmp[$f];
            }
            if (!isset($new_arr[$tmp])) {
                $new_arr[(string)$tmp] = $av;
            }
        }
        return $new_arr;
    }
}

/**
 * 生成随机字符串
 */
if (!function_exists('createRandomStr')) {
    function createRandomStr(): string
    {
        return \Hyperf\Stringable\Str::random(10) . uniqid();
    }
}

/**
 * 生成多个随机字符串数组
 */
if (!function_exists('randStrs')) {
    function randStrs(int $qty = 1, array $notStrs = []): array
    {
        $res = [];
        $dict = 'abcdefghijklmnopqrstuvwxyz';
        while (true) {
            $arr = \Hyperf\Collection\Arr::random(str_split($dict), mt_rand(5, 10));
            $str = join('', $arr);
            if (strlen($str) > 4 && !in_array($str, $notStrs)) {
                $res[] = $str;
                if (count($res) >= $qty) {
                    return $res;
                }
            }
        }
    }
}

/**
 * 获取客户端你真实IP
 * @return mixed|string
 */
if (!function_exists('getRealIp')) {
    function getRealIp(): string
    {
        if ($ip = request()->getHeaderLine('x-real-ip')) {
            return $ip;
        } else if ($ip = request()->getHeaderLine('x-forwarded-for')) {
            return $ip;
        }
        return request()->getServerParams()['remote_addr'] ?? '';
    }
}

/**
 * 获取客户端的user-agent
 */
if (!function_exists('getUserAgent')) {
    function getUserAgent(): string
    {
        return request()->getHeaders()['user-agent'][0] ?? '';
    }
}

/**
 * 获取客户端的user-agent
 */
if (!function_exists('getAcceptLanguage')) {
    function getAcceptLanguage(): string
    {
        return request()->getHeaders()['accept-language'][0] ?? '';
    }
}

/**
 * 获取当前请求URI
 */
if (!function_exists('getRequestUri')) {
    function getRequestUri(): string
    {
        return request()->getServerParams()['request_uri'] ?? '';
    }
}

/**
 * 获取当前Get请求参数
 */
if (!function_exists('getQueryString')) {
    function getQueryString(): string
    {
        return request()->getServerParams()['query_string'] ?? '';
    }
}

/**
 * 获取当前Get请求参数
 */
if (!function_exists('getQueryParams')) {
    function getQueryParams(): array
    {
        return request()->getQueryParams();
    }
}

/**
 * 获取当前Post请求参数
 */
if (!function_exists('getRequestParsedBody')) {
    function getRequestParsedBody()
    {
        return request()->getParsedBody();
    }
}

/**
 * 获取当前请求方法
 */
if (!function_exists('getRequestMethod')) {
    function getRequestMethod()
    {
        return request()->getServerParams()['request_method'] ?? '';
    }
}

if (!function_exists('getMicrotime')) {
    function getMicrotime()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}